package com.youdo.careyes.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ThreadUtils;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.youdo.careyes.MyApp;
import com.youdo.careyes.R;
import com.youdo.careyes.databinding.FragmentFilesBinding;
import com.youdo.careyes.utils.VideoFileSearcher;
import com.youdo.careyes.widget.MediaPlayerDialog;

import java.util.List;

/**
 * 文件管理
 */
public class FilesFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    private static final String TAG = "FilesFragment";
    private FragmentFilesBinding binding;
    FileItemAdapter adapter;
    MediaPlayerDialog playerDialog;
    int currentPosition = 0;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentFilesBinding.inflate(inflater, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        adapter = new FileItemAdapter(getActivity(), binding.tvNum);
        binding.gridView.setAdapter(adapter);
        binding.gridView.setOnItemClickListener(this);
        binding.ivVideo.setNextFocusDownId(binding.ivPic.getId());
//        binding.ivAudio.setNextFocusDownId(binding.ivPic.getId());
//        binding.ivAudio.setNextFocusUpId(binding.ivVideo.getId());
        binding.ivPic.setNextFocusUpId(binding.ivVideo.getId());
        binding.ivVideo.setOnClickListener(this);
//        binding.ivAudio.setOnClickListener(this);
        binding.ivPic.setOnClickListener(this);
        playerDialog = new MediaPlayerDialog(getActivity(), 0);
        binding.gridView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
                if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_UP) {
                    if (currentPosition == 0) {
                        // currentPosition = adapter.getCount() - 1;
                        binding.cbDelete.requestFocus();
                        return true;
                    } else {
                        currentPosition--;
                    }
                    binding.gridView.setSelection(currentPosition);
                    return true;
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
                    if (currentPosition == 0) {
                       // currentPosition = adapter.getCount() - 1;
                    } else {
                        currentPosition--;
                    }
                    binding.gridView.setSelection(currentPosition);
                    return true;
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
                    currentPosition++;
                    if (currentPosition == adapter.getCount()) {
                     //   currentPosition = 0;
                        currentPosition = adapter.getCount()-1;
                    }
                    binding.gridView.setSelection(currentPosition);
                    return true;
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
                    currentPosition++;
                    if (currentPosition == adapter.getCount()) {
                     //   currentPosition = 0;
                        currentPosition = adapter.getCount()-1;
                    }
                    binding.gridView.setSelection(currentPosition);
                    return true;
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
                    onItemClick(null, null, currentPosition, currentPosition);
                    return true;
                } else if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
                    onItemClick(null, null, currentPosition, currentPosition);
                    return true;
                }
                return false;
            }
        });
        binding.gridView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                currentPosition = i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        binding.tvNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.next();
            }
        });
        binding.tvPrevious.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.previous();
            }
        });
    }

    @Override
    public void onClick(View view) {
        WaitDialog.show(getString(R.string.app_public_loading));
        if (binding.ivVideo == view) {
//            filesSearchTask.setType(0);
            initData(0);
        } else if (binding.ivPic == view) {
//            filesSearchTask.setType(2);
            initData(2);
        }
//        ThreadUtils.executeByIo(filesSearchTask);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        VideoFileSearcher.VideoInfo info = adapter.getItem(i);
        if (binding.cbDelete.isChecked()) {
            WaitDialog.show(getString(R.string.app_public_deleting));
            Log.e(TAG, "删除文件: " + FileUtils.delete(info.path) + "," + info);
            initData(info.type);
//            ThreadUtils.executeByCpu(filesSearchTask);
/*            MessageDialog.show("确定要删除文件?", "").setOkButton("确定删除", new OnDialogButtonClickListener<MessageDialog>() {
                @Override
                public boolean onClick(MessageDialog dialog, View v) {
                    return false;
                }
            });*/
        } else {
            playerDialog.showVideo(info);
            playerDialog.show();
        }
    }

    // -----------------文件扫描任务;by ljb 20251106;
    abstract static class FilesSearchTask extends ThreadUtils.Task<List<VideoFileSearcher.VideoInfo>> {
        private int type = 0;// 2-图片 其他-视频

        public FilesSearchTask(int type) {
            this.type = type;
        }

        public void setType(int type) {
            this.type = type;
        }

        @Override
        public List<VideoFileSearcher.VideoInfo> doInBackground() {
            Log.e(TAG, "查询文件: " + type);
            return VideoFileSearcher.getAllVideos(MyApp.getApplication(), type);// 0/2
        }
    }

    private void initData(int type) {
        ThreadUtils.executeByIo(new FilesSearchTask(type) {
            private static final String TAG = "FilesSearchTask";

            @Override
            public void onSuccess(List<VideoFileSearcher.VideoInfo> list) {
                Log.e(TAG, "查询视频成功: 一共 " + list.size());
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        WaitDialog.dismiss();
                        adapter.notifyDataChange(list);
                        binding.gridView.setVisibility(View.VISIBLE);
                        binding.llFun.setVisibility(View.GONE);
                        binding.llFileManage.setVisibility(View.VISIBLE);
                    }
                });
            }

            @Override
            public void onCancel() {
                Log.e(TAG, "onCancel: ");
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        WaitDialog.dismiss();
                    }
                });
            }

            @Override
            public void onFail(Throwable throwable) {
                Log.e(TAG, "onFail: ");
                ThreadUtils.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        WaitDialog.dismiss();
                    }
                });
            }
        });
    }
}
